<template>
  <div class="base-info-page">
    <!-- 上传弹窗 -->
    <div class="uploadModal-wrap" v-if="showUpload">

      <div class="flex-box">
        <div class="flex-item" style="flex-grow: 1;width:868px;">
          <div>
            <Tabs v-model='currentTab' style="background: #f3f3f4;">
              <TabPane label="本地上传" name="name1">
                <!-- <div class="upload-tip-div">
                 <img class="upload-tip" src="../../../../assets/images/upload-tip.png" />
                </div> -->
                <div class="img-list">
                  <div class="flex-start-box">
                    <Select v-model="data.uploadparams.dirType" style="width:105px" placeholder="上传到">
                      <Option v-for="item in optionObj" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                    <span style="margin-left: 20px;margin-right: 10px;">上传文件类型:</span>
                    <RadioGroup v-model="data.uploadparams.class">
                      <Radio :label="item.id" v-for="(item,index) in fileType">{{item.name}}</Radio>
                    </RadioGroup>
                    <Upload :accept='acceptImgType' :headers='headers' :action='imgApi+"/upload/index"' :data='data.uploadparams'
                      ref="upload" :show-upload-list="false" :default-file-list="defaultList" :on-success="handleSuccess"
                      :format="['jpg','jpeg','png','mp4','gif']" :max-size="20000048" :on-format-error="handleFormatError"
                      :on-exceeded-size="handleMaxSize" :before-upload="handleBeforeUpload" multiple type="drag" style="display: inline-block;"
                      class="marginleft10">
                      <Button type='primary'  icon="md-cloud-upload">本地上传</Button>
                    </Upload>
                  </div>
                  <div class="innder flex-start-box">
                    <div @click="selectImg(item,index)" @mouseleave="mouseleave($event,item,index)" @mouseenter="mouseenter($event,item,index)"
                      v-for="(item,index) in data.imgList" :key='item.id' class="img-box" :class="indexArr.indexOf(index)>-1 ? 'border' : ''">
                      <Icon @click.stop='delImg(item,index)' v-show='current==index' type="md-close" class="delete-img-icon" />
                      <Icon type="md-checkmark" v-show='indexArr.indexOf(index)>-1' class="select-img-icon" />

                      <video style="width:80px;height:80px;" v-if="item.type=='video/mp4'" :src="item.url"></video>
                      <img v-else :src="item.url" />
                      <div>{{item.name}}</div>
                    </div>
                  </div>
                </div>
              </TabPane>
              <TabPane label="相册图片" name="name2">
                <div class="img-list">
                  <div class="flex-start-box">
                    <Select v-model="searchDirType" @on-change='changeDirType($event,"img")' style="width:105px"
                      placeholder="请选择">
                      <Option v-for="item in optionObj" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                  </div>
                  <div class="innder flex-start-box">
                    <div @click="selectImg(item,index)" @mouseleave="mouseleave($event,item,index)" @mouseenter="mouseenter($event,item,index)"
                      v-for="(item,index) in data.photo_album_list" :key='item.id' class="img-box" :class="indexArr.indexOf(index)>-1 ? 'border' : ''">
                      <Icon @click='delImg(item,index)' v-show='current==index' type="md-close" class="delete-img-icon" />
                      <Icon type="md-checkmark" v-show='indexArr.indexOf(index)>-1' class="select-img-icon" />
                      <video style="width:80px;height:80px;display: block;" v-if="item.extension && item.extension=='mp4'"
                        :src="item.url"></video>
                      <img v-else :src="item.url" />
                      <div class="text-overflow">{{item.file_name}}</div>
                    </div>
                  </div>
                  <Page class="foot-page text-center" :current='page.current' :total="page.total" :page-size="page.pageSize"
                    show-total show-elevator @on-change="changepage"></Page>
                </div>
              </TabPane>
             <!-- <TabPane label="视频" name="name3">

                <div class="img-list">
                  <div class="flex-start-box">
                    <Select v-model="searchDirType" @on-change='changeDirType($event,"video")' style="width:105px"
                      placeholder="请选择">
                      <Option v-for="item in optionObj" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                  </div>
                  <div class="innder flex-start-box">
                    <div @click="selectImg(item,index)" @mouseleave="mouseleave($event,item,index)" @mouseenter="mouseenter($event,item,index)"
                      v-for="(item,index) in data.video_list" :key='item.id' class="img-box" :class="indexArr.indexOf(index)>-1 ? 'border' : ''">
                      <Icon @click='delImg(item,index)' v-show='current==index' type="md-close" class="delete-img-icon" />
                      <Icon type="md-checkmark" v-show='indexArr.indexOf(index)>-1' class="select-img-icon" />
                      <video style="width:80px;height:80px;display: block;" v-if="item.extension && item.extension=='mp4'"
                        :src="item.url"></video>
                      <img v-else :src="item.url" />
                      <div class="text-overflow">{{item.file_name}}</div>
                    </div>
                  </div>
                  <Page class="foot-page text-center" :current='page.current' :total="page.total" :page-size="page.pageSize"
                    show-total show-elevator @on-change="changepage"></Page>
                </div>
              </TabPane> -->

            </Tabs>
          </div>
        </div>
        <div class="flex-item" style="width:160px; position: absolute;right: 17px;">
          <div class="select-box">
            <div class="select-box-inner">
              <p class="select-box-inner-title">待添加文件</p>
              <div class="select-box-img">
                <div class="img-div" v-for="(item,index) in data.waitImgList" @mouseleave="fileLeave($event,item,index)"
                  @mouseenter="fileEnter($event,item,index)">
                  <div key='file-action' v-show='fileCurrent==index' class="action-btn">
                    <Icon type="md-arrow-up" @click="upMove(item,index)" />
                    <Icon type="md-close" @click="remove(item,index)" />
                    <Icon type="md-arrow-down" @click="downMove(item,index)" />
                  </div>
                  <video style="width:80px;height:80px;" v-if="item.extension && item.extension=='mp4' || item.type=='video/mp4'"
                    :src="item.url"></video>
                  <img v-else :src="item.url" />
                </div>


              </div>
            </div>

          </div>
        </div>
      </div>

    </div>
    <!-- 上传end -->
    <!-- 删除弹窗 -->
    <Modal v-model="delModal" title="提示">
      <p class="font16">
        <Icon class='del-tips-icon' type="ios-alert-outline" color='orange' size='22' />确定要删除吗？</p>
      <div slot="footer">
        <Button @click='delModal=false'>取消</Button>
        <Button type="primary" @click='confirmDel'>确定</Button>
      </div>
    </Modal>
    <!--  -->
  </div>
</template>
<!-- 公共弹框，成功，失败，报错，loading -->
<script>
  import Tables from '_c/tables'
  // 接口
  import {
    upload,
    getAlbumList,
    getVideoList,
    delUpload
  } from '@/api/data'
  import {
    mapState
  } from 'vuex'

  export default {
    name: 'tables_page',
    components: {
      Tables
    },
    created() {

      this.headers.Authorization = this.keyToken;
      this.data.imgList = []
    },
    watch: {

      showUpload(newName, oldName) {

        if (newName) {
          // 重新打开弹窗，初始化
          this.data.imgList = [];
          this.currentTab = 'name1';
          this.selectImgList = [];
          this.data.waitImgList = [];
          this.indexArr = []
        }
      },
      currentTab(newName) {
        this.searchDirType = 0; //切换初始

        if (newName == 'name2') {

          this.getAlbumList()

        } else if (newName == 'name3') {
          this.getVideoList()
        }
      }

    },
    mounted() {
      //this.uploadList = this.$refs.upload.fileList;

    },
    props: ['showUpload', 'optionObj'],
    computed: {
      ...mapState({
        prodGroupBasicObj: state => state.share.prodGroupBasicObj,
        keyToken: state => state.user.keyToken
      }),
    },
    data() {
      return {
        // 上传
        fileType: [{
          name: '相册',
          id: 1
        },
        // {
        //   name: '视频',
        //   id: 2
        // },
        ],
        acceptImgType: 'image/jpeg,image/jpg,image/png,video/mp4,image/gif',
        currentTab: 'name1',
        headers: {
          Authorization: this.keyToken
        },
        imgApi: '/v1',
        delModal: false,
        maskClosable: false,
        // 分页
        page: {
          size: 21,
          current: 1,
          total: 0
        },
        // 分页end
        searchDirType: '', //
        indexArr: [],
        selectImgList: [],
        selectCurrent: null,
        fileCurrent: null,
        current: null,

        uploadList: [], //

        defaultList: [],
        uploadModal: true,

        // 上传end
        formValidate: {},
        tableData: [],

        data: {
          waitImgList: [], //待添加文件
          imgList: [],
          video_list: [],
          photo_album_list: [], //相册
          uploadparams: {
            //name:'1.png',
            dirType: 0,
            class: 1, //默认相册
            //saveType: 0,
            userType: 1,
            //sourceType: 0
          }
        },
        delId: '',
        editIndex: 0, // 当前聚焦的输入框的行数
        editName: '', // 第一列输入框，当然聚焦的输入框的输入内容，与 data 分离避免重构的闪烁
        editAge: '', // 第二列输入框
        editBirthday: '', // 第三列输入框
        editAddress: '', // 第四列输入框
      }
    },
    methods: {
      // 列表数据
      getList() {

        let type = 'success'
        // this.$Message[type]({
        //   background: true,
        //   content: '这是一条带背景色的通知'
        // });

      },
      //上传
      changeDirType(e, type) {


        this.data.photo_album_list = []; //初始化
        this.data.video_list = []; //初始化
        this.page.total = 0;
        this.searchDirType = e;
        if (type === 'img') {
          this.getAlbumList()
        } else {
          this.getVideoList()
        }


      },
      getAlbumList() {
        let _this = this
        let params = {
          page: this.page.current,
          // size:this.page.size,
          dir_type: this.searchDirType,

        }
        getAlbumList(params).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data;

            _this.data.photo_album_list = result.list;
            this.page.total = result.total


          }

        }).catch(function(error) {
          //异常
          console.log(error)
        })

      },
      getVideoList() {
        let _this = this
        let params = {
          page: this.page.current,
          // size:this.page.size,
          dir_type: this.searchDirType,

        }
        getVideoList(params).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data;

            _this.data.video_list = result.list;
            this.page.total = result.total


          }

        }).catch(function(error) {
          //异常
          console.log(error)
        })

      },
      changepage(e) {
        this.page.current = e;
        this.getAlbumList()
      },
      closeModel() {

      },
      delImg(row, index) {
        console.log(row)
        this.delModal = true;
        this.delId = row.id;

      },
      confirmDel() {
        console.log(123)
        let _this = this;
        let obj = {
          id: this.delId
        }
        delUpload(obj).then(res => {
          if (res.data.status == 1) {
            _this.delModal = false;
            _this.$Message.success('操作成功');
            if (_this.currentTab == 'name2') {
              _this.getAlbumList();
            } else if (_this.currentTab == 'name3') {
              _this.getVideoList()
            } else {
              // 上传的时候
              let i = '';
              let newList=[]
              for(let i=0; i<_this.data.imgList.length; i++){
                 if (_this.delId ==_this.data.imgList[i].id) {
                   i =i;

                   _this.data.imgList.splice(i, 1)
                   break;
                 }
              }



              // _this.data.imgList=_this.data.imgList.splice(k, 1)

              //data.imgList
            }


          } else {
            _this.delModal = false;
            //axios响应拦截
          }
        }).catch(function(error) {
          //异常
          _this.delModal = false;
          console.log(error)
        })

      },
      changeSort(arr, index, type) {
        // 上移 type 为 0， 下移为 1.
        return arr.splice(type ? index : index - 1, 1, ...arr.splice(type ? index + 1 : index, 1, arr[type ? index :
          index - 1]));
      },
      remove(row, index) {
        this.data.waitImgList.splice(index, 1)

      },
      upMove(row, index) {

        if (index === 0) return false
        // 将上一个数组元素值替换为当前元素值，并将被替换的元素值赋值给当前元素
        this.data.waitImgList[index] = this.data.waitImgList.splice(index - 1, 1, this.data.waitImgList[index])[0]
        return this.data.waitImgList


      },
      downMove(row, index) {
        if (index === this.data.waitImgList.length - 1) return false
        // 将上下个数组元素值替换为当前元素值，并将被替换的元素值赋值给当前元素
        this.data.waitImgList[index] = this.data.waitImgList.splice(index + 1, 1, this.data.waitImgList[index])[0]
        return this.data.waitImgList



      },
      confirm() {

      },
      selectImg(row, index) {
        //this.indexArr用来记录选中图片的索引，判断打勾
        let arrIndex = this.indexArr.indexOf(index); //数组中是否已经存在
        if (arrIndex > -1) {
          // 存在，点击的时候就删除
          this.indexArr.splice(arrIndex, 1);
          this.selectImgList.splice(arrIndex, 1);
        } else {
          // 不存在点击就添加
          this.indexArr.push(index); //索引
          this.selectImgList.push(row); //图片整条数据
        }

        this.data.waitImgList = this.selectImgList;

        // 子组件传值给父组件，即将选中的图片传过去
        this.$emit('getSelectedImgList', this.data.waitImgList)


      },
      mouseleave(event, row, index) {
        this.current = null;
      },
      mouseenter(event, row, index) {
        this.current = index;
      },
      fileLeave(event, row, index) {
        this.fileCurrent = null;
      },
      fileEnter(event, row, index) {

        this.fileCurrent = index;
      },
      handleView(name) {
        this.imgName = name;
        this.visible = true;
      },
      handleRemove(file) {
        const fileList = this.$refs.upload.fileList;
        this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
      },
      handleSuccess(res, file) {
        console.log(res)
        let result = res.data;
        let obj = {
          id: result.id,
          name: result.name,
          path_name: result.path,
          url: result.url,
          type: result.type
        }
        this.data.imgList.push(obj)

        // file.url = 'https://o5wwk8baw.qnssl.com/7eb99afb9d5f317c912f08b5212fd69a/avatar';
        // file.name = '7eb99afb9d5f317c912f08b5212fd69a';

      },
      handleFormatError(file) {

        this.$Notice.warning({
          title: 'The file format is incorrect',
          desc: 'File format of ' + file.name + '文件格式不正确，请上传格式为png,jpg,jpeg的图片'
        });
      },
      handleMaxSize(file) {
        this.$Notice.warning({
          title: 'Exceeding file size limit',
          desc: 'File  ' + file.name + '太大，请上传小于2M的图片.'
        });
      },
      handleBeforeUpload(file) {
        console.log(file.type)
        let type = file.type;
        let arr = ['image/png', 'image/jpg', 'image/jpeg'];
        let isUpload = true;
        if (this.data.uploadparams.class == 1) {
          // 相册
          if (arr.indexOf(type) >= 0) {
            isUpload = true;
          } else {
            isUpload = false
          }

        } else {
          if (arr.indexOf(type) >= 0) {
            isUpload = false;
          } else {
            isUpload = true
          }

        }

        if (!isUpload) {
          this.$Notice.warning({
            title: '上传文件类型不正确'
          });
          return
        }
        // const check = this.uploadList.length < 5;
        // if (!check) {
        //   this.$Notice.warning({
        //     title: '一次最多可以上传五张图片'
        //   });
        // }
        // return check;
      },
      // 上传end

    },

  }
</script>

<style lang="scss">
  @import "./uploadTool";
</style>
